HackerRank Sherlock and Anagrams
https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem
解答
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
#
# Complete the 'sherlockAndAnagrams' function below.
#
# The function is expected to return an INTEGER.
# The function accepts STRING s as parameter.
#
def sherlockAndAnagrams(s):
# Write your code here
count = 0
# len(1)
dic = Counter(s)
# abba
for i in range(2, len(s)):
# ab, abb
sb = s0:i
l = len(sb)
dic"".join(sorted(sb)) += 1
# bb, ba
for j in range(1, len(s)):
if j + l <= len(s):
dic["".join(sorted(sj:j+l))] += 1
# print(dic)
# Counter({'a': 2, 'b': 2, 'ab': 2, 'abb': 2, 'bb': 1})
for k, v in dic.items():
count += v*(v-1) // 2
return count
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
q = int(input().strip())
for q_itr in range(q):
s = input()
result = sherlockAndAnagrams(s)
fptr.write(str(result) + '\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=3fpSbdzR6Pc
https://scrapbox.io/files/61cfa044b79186002095d2c4.png
https://scrapbox.io/files/61cfa0495e31b7001d8f1699.png
https://scrapbox.io/files/61cfa04d2b9a62001d916fcc.png
https://scrapbox.io/files/61cfa0510c499e001daa7ba7.png
https://scrapbox.io/files/61cfa05628c0e20021f557b1.png
https://scrapbox.io/files/61cfa0606e7de0001f0f8df7.png
提出
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
import collections
#
# Complete the 'sherlockAndAnagrams' function below.
#
# The function is expected to return an INTEGER.
# The function accepts STRING s as parameter.
#
def sherlockAndAnagrams(s):
# Write your code here
c = collections.Counter(list(s))
print(c)
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
q = int(input().strip())
for q_itr in range(q):
s = input()
result = sherlockAndAnagrams(s)
fptr.write(str(result) + '\n')
fptr.close()